package com.tonggedata.dataapi.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class JDBCUtils {
    //所有数据源的连接池存在map里
    static ConcurrentHashMap<String, DruidDataSource> map = new ConcurrentHashMap<>();

    public static DruidPooledConnection getJdbcConnectionPool(Properties properties) throws SQLException {
        String dbname = properties.getProperty("dbname");
        String id = String.valueOf(dbname.hashCode());

        if (map.containsKey(id)) {
            return map.get(id).getConnection();
        } else {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setName(dbname);
            druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/"+dbname+"information_schema?useSSL=false&serverTimezone=GMT%2B8");
            druidDataSource.setUsername(properties.getProperty("username"));
            druidDataSource.setPassword(properties.getProperty("password"));
            druidDataSource.setDriverClassName(properties.getProperty("driverClassName"));
            druidDataSource.setConnectionErrorRetryAttempts(3);       //失败后重连次数
            druidDataSource.setBreakAfterAcquireFailure(true);

    //        try {
    //            druidDataSource.setPassword(DESUtils.decrypt(ds.getPassword()));
    //        } catch (Exception e) {
    //            throw new RuntimeException(e);
    //        }

            map.put(String.valueOf(id), druidDataSource);
    //        log.info("create druid datasource：{}", druidDataSource.getName());
            return druidDataSource.getConnection();
        }
    }

//    //删除数据库连接池
//    public static void removeJdbcConnectionPool(String id) {
//        if (map.containsKey(id)) {
//            DruidDataSource old = map.get(id);
//            map.remove(id);
//            old.close();
//            log.info("remove druid datasource: {}", old.getName());
//        }
//    }

//    public static DruidPooledConnection getPooledConnection(DataSource ds) throws SQLException {
//        DruidDataSource pool = PoolManager.getJdbcConnectionPool(ds);
//        DruidPooledConnection connection = pool.getConnection();
////        log.info("获取连接成功");
//        return connection;
//    }
}
